package scau.mis4.chanyulin.atm.base.utils;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * Created by cyl on 2017/12/4.
 * 数据库工具类
 */
public class DbUtils {

    private static final String CONFIG_FILE_PATH = "/config/database-config.properties";
    private static final String DB_DRIVER = "com.mysql.jdbc.Driver";
    private static Properties configFile;
    private static String url;
    private static String user;
    private static String password;
    private static Connection conn;
    private static Statement stat;

    // 初始化
    static {
        initConfigFile();
        initConfigInfo();
        initConn();
    }

    public static Statement getStatement() {
        if (stat == null) {
            if (conn == null) initConn();
            else initStat();
        }
        return stat;
    }

    private static void initConfigFile() {
        try {
            configFile = PropUtils.loadProperties(CONFIG_FILE_PATH);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void initConfigInfo() {
        url = PropUtils.getPropValue(configFile, "url");
        user = PropUtils.getPropValue(configFile, "user");
        password = PropUtils.getPropValue(configFile, "password");
    }

    private static void initConn() {
        try {
            Class.forName(DB_DRIVER);
            try {
                if (configFile == null)
                    initConfigFile();
                if (url == null || user == null || password == null)
                    initConfigInfo();
                conn = DriverManager.getConnection(url, user, password);
                stat = conn.createStatement();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private static void initStat() {
        try {
            stat = conn.createStatement();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static String getUrl() {
        return url;
    }

    public static String getIP() {
        return RegUtils.getIP(url);
    }

    public static String getDbName() {
        return RegUtils.getDbNameFromUrl(getUrl());
    }

}
